package cn.iotab.iotkit.transport.api.driver.context;

import cn.iotab.iotkit.transport.api.common.message.msg.up.SessionInfo;
import cn.iotab.iotkit.transport.api.driver.DriverSession;
import lombok.Getter;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * SessionContext在TCP连接建立之后生成
 * DriverSession在设备认证成功之后生成
 */
public abstract class SessionContext {

    private final AtomicInteger msgIdSeq = new AtomicInteger(0);

    private final String sessionId;

    @Getter
    private DriverSession driverSession;

    private volatile boolean connected;

    /**
     * Constructor
     *
     * @param sessionId
     */
    protected SessionContext(String sessionId) {
        this.sessionId = sessionId;
    }

    public void setDriverSession(DriverSession driverSession) {
        this.driverSession = driverSession;
        this.connected = true;
    }

    public SessionInfo getSessionInfo() {
        if (driverSession == null) return null;
        return driverSession.getSessionInfo();
    }

    public boolean isConnected() {
        return connected;
    }

    /**
     * set session connected
     * 设备认证成功后setConnected
     */
    public void setConnected() {
        this.connected = true;
    }

    /**
     * set session disconnected
     */
    public void setDisconnected() {
        this.connected = false;
    }

    /**
     * sessionId
     *
     * @return
     */
    public String getSessionId() {
        return sessionId;
    }

    /**
     * mextMsgId
     *
     * @return
     */
    public int nextMsgId() {
        return msgIdSeq.incrementAndGet();
    }
}
